var express = require('express');
var router = express.Router();
var {usermodel} = require('../database/model/clientModel.js')
var bcrypt = require('bcryptjs');  //加密模块
var salt = bcrypt.genSaltSync(10); //加密盐
var jwt = require('jsonwebtoken')
var secret = 'alskdjflasjdkflasjdklfjaldsf45a234s$$$q2323@@d65fa6sd4f6asd45f6asdfasdfasdfa321321asdf'

// 注册
router.post('/',(req,res)=>{
  // console.log(req.body);
  let {username,password}  = req.body
  usermodel.find({username}).then(result=>{
    console.log(result);
    if(result.length!=0){
      res.send({
        code:110,
        msg:'账号已被占用'
      })
      return
    }
    // 密码加密
    var hash = bcrypt.hashSync(password, salt); //密码加密
    console.log(hash);
    new usermodel({
      username,
      hash
    }).save().then(result=>{
      res.send({
        code:111,
        msg:'注册成功'
      })
    })
  })
})

//登录
router.get('/', function(req, res) {
  console.log(req.query);
  let {username,password} = req.query
  usermodel.find({username}).then(result=>{
    if(result.length==0){  //账号不存在
      res.send({
        code:110,
        msg:'账号不存在，请注册'
      })
      return
    }
    let {hash} = result[0] //提取当前账号存在数据库中的加密密码
    let bool = bcrypt.compareSync(password, hash); //密码比对，返回值是布尔值
    if(!bool){ //密码错误
      res.send({
        code:112,
        msg:'密码错误，请重试'
      })
      return
    }
    let userInfo = result[0]  //数据库查出的对象，跟普通的js对象操作有差异
    userInfo.hash = ''
    jwt.sign({
      time:Date.now(),   //签发token的时间戳
      // limit:7*24*60*60*1000  //有效时长
      limit:30*1000  //有效时长
    },secret,(err,token)=>{
      let {username,_id,avatar} = userInfo
      console.log(token);
      res.send({ 
        code:111,
        msg:'登录成功',
        data:{
          username,
          _id,
          avatar,
          token,
          authToken:token,
          sign:token
        }
      })
    })
  })
});



module.exports = router;
